const express = require("express");
const multer = require("multer");
// 原文档中没有的 constant/ 和 Result 文件
const { UPLOAD_PATH } = require("../utils/constant");
const Result = require("../../models/Result");

const { env } = require("./env");
const UPLOAD_PATH =
  env === "dev"
    ? "/Users/sam/upload/admin-upload-ebook"
    : "/root/upload/admin-upload-ebook";

const router = express.Router();

router.post(
  "/upload",
  multer({ dest: `${UPLOAD_PATH}/book` }).single("file"),
  function(req, res, next) {
    if (!req.file || req.file.length === 0) {
      new Result("上传电子书失败").fail(res);
    } else {
      const book = new Book(req.file);
      book
        .parse()
        .then(book => {
          new Result(book.toJson(), "上传电子书成功").success(res);
        })
        .catch(err => {
          console.log("/book/upload", err);
          next(boom.badImplementation(err));
          book.reset();
        });
    }
  }
);
